package com.cll.controller.user;


import com.cll.constant.JwtClaimsConstant;
import com.cll.dto.UserLoginDTO;
import com.cll.entity.User;
import com.cll.properties.JwtProperties;
import com.cll.result.Result;
import com.cll.service.UserService;
import com.cll.utils.JwtUtil;
import com.cll.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     *用户登录
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录接口：{}",userLoginDTO);

        //1.调用业务进行用户登录操作，返回用户对象
        User user = userService.wxLogin(userLoginDTO);

        //2.创建载荷，将用户id写入载荷
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());

        //3.生成令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        //4.构建UserLoginVO对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        //5.返回数据
        return Result.success(userLoginVO);
    }
}
